package com.car.json;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.car.bean.PCAtuoBrand;
import com.car.dao.PCAuto;
import com.car.util.DocUtil;
import com.car.util.Util;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class PCAutoJSON {
	private PCAuto dao = new PCAuto();

	// 得到最大的品牌ID（bid） 宝马693 奥迪1
	public List<Integer> getBid() {
		List<Integer> bids = new ArrayList<>();
		String url = "http://price.pcauto.com.cn/cars/";
		Document doc = DocUtil.getDoc(url);
		Elements carList = doc.select("div.dFix a");
		for (Element car : carList) {
			String link = car.attr("href");
			int bid = Integer.parseInt(link.split("nb")[1].split("/")[0]);
			bids.add(bid);
		}
		return bids;
	}

	public void parseJson(int bid) {
		JSONArray jsonarray;
		JSONObject jsonObj;
		String url = "http://price.pcauto.com.cn/api/hcs/select/dashouye/serialgroup_json_chooser?bid=" + bid
				+ "&callback=firm_3callback";
		Document doc = null;
		try {
			doc = Jsoup.connect(url).timeout(30000).get();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String s = doc.body().text();
		String jsonData = Util.getMatched(s, "(\\[)(.{1,})(\\])").group(0);
		jsonarray = JSONArray.fromObject(jsonData);
		for (int i = 0; i < jsonarray.size(); i++) {
			try {
				JSONObject job = jsonarray.getJSONObject(i);
				int pcauto_id = Integer.parseInt(job.get("id").toString());
				String pcauto_name = job.get("name").toString();
				int pcauto_sell_status = Integer.parseInt(job.get("sell_status").toString());
				int pcauto_car_field = Integer.parseInt(job.get("car_field").toString());
				int pcauto_car_version = Integer.parseInt(job.get("car_version").toString());
				String pcauto_tip = job.get("tip").toString();
				PCAtuoBrand pb = new PCAtuoBrand(pcauto_id, pcauto_name, pcauto_sell_status, pcauto_car_field,
						pcauto_car_version, pcauto_tip);
				dao.insertPCAutoBrand(pb);
			} catch (Exception e) {
				continue;
			}
		}
	}

	public static void main(String[] args) {
		PCAutoJSON p = new PCAutoJSON();
		List<Integer> list = p.getBid();
		for (Integer i : list) {
			p.parseJson(i);
		}
	}
}
